package com.test.platform.service.publish;

import com.test.platform.dao.PublishInfoMapper;
import com.test.platform.model.PublishInfo;
import com.test.platform.websocket.WebSocketService;
import com.test.platform.websocket.WebSocketMessage;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Service
public class PublishDataProcessor {
    private static final Logger logger = LoggerFactory.getLogger(PublishDataProcessor.class);

    @Autowired
    private PublishInfoMapper publishInfoMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private WebSocketService webSocketService;

    // 统一处理发布信息的创建和更新
    public CompletableFuture<Boolean> processPublishInfo(PublishInfo publishInfo) {
        String lockKey = "publish_info_lock:" + publishInfo.getOwner() + ":" + publishInfo.getName();
        RLock lock = redissonClient.getLock(lockKey);
        
        try {
            if (!lock.tryLock(5, 10, TimeUnit.SECONDS)) {
                logger.warn("无法获取分布式锁，跳过更新: {}/{}", publishInfo.getOwner(), publishInfo.getName());
                return CompletableFuture.completedFuture(false);
            }

            var existingInfos = publishInfoMapper.findByOwnerAndName(publishInfo.getOwner(), publishInfo.getName());
            boolean result;
            
            if (existingInfos != null && !existingInfos.isEmpty()) {
                publishInfo.setId(existingInfos.get(0).getId());
                result = publishInfoMapper.update(publishInfo) > 0;
                logger.info("更新发布信息: {}", publishInfo);
            } else {
                result = publishInfoMapper.insert(publishInfo) > 0;
                logger.info("创建发布信息: {}", publishInfo);
            }

            if (result) {
                notifyUpdate(publishInfo);
            }

            return CompletableFuture.completedFuture(result);
        } catch (Exception e) {
            logger.error("处理发布信息时发生错误: {}/{}", publishInfo.getOwner(), publishInfo.getName(), e);
            return CompletableFuture.completedFuture(false);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    // 处理提交信息更新
    public CompletableFuture<Boolean> processCommitInfo(String owner, String name, String version, 
            String commitSha, String changelog) {
        PublishInfo publishInfo = new PublishInfo();
        publishInfo.setOwner(owner);
        publishInfo.setName(name);
        publishInfo.setVersion(version);
        publishInfo.setCommitId(commitSha != null ? commitSha : "initial");
        publishInfo.setChangeLog(changelog != null ? changelog : "No changelog available");
        
        return processPublishInfo(publishInfo);
    }

    // 处理状态更新
    public CompletableFuture<Boolean> updatePublishStatus(String owner, String name, String status) {
        String lockKey = "publish_info_lock:" + owner + ":" + name;
        RLock lock = redissonClient.getLock(lockKey);
        
        try {
            if (!lock.tryLock(5, 10, TimeUnit.SECONDS)) {
                logger.warn("无法获取分布式锁，跳过状态更新: {}/{}", owner, name);
                return CompletableFuture.completedFuture(false);
            }

            var existingInfos = publishInfoMapper.findByOwnerAndName(owner, name);
            if (existingInfos != null && !existingInfos.isEmpty()) {
                PublishInfo publishInfo = existingInfos.get(0);
                publishInfo.setStatus(status);
                boolean result = publishInfoMapper.update(publishInfo) > 0;
                
                if (result) {
                    notifyUpdate(publishInfo);
                }
                
                return CompletableFuture.completedFuture(result);
            }
            
            return CompletableFuture.completedFuture(false);
        } catch (Exception e) {
            logger.error("更新发布状态时发生错误: {}/{}", owner, name, e);
            return CompletableFuture.completedFuture(false);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    // 统一的 WebSocket 通知
    private void notifyUpdate(PublishInfo publishInfo) {
        try {
            String message = String.format("发布信息已更新: %s/%s", publishInfo.getOwner(), publishInfo.getName());
            webSocketService.sendMessage("refresh", new WebSocketMessage("refresh", null, message));
            logger.info("已发送更新通知: {}", message);
        } catch (Exception e) {
            logger.error("发送更新通知失败", e);
        }
    }
}